//
//  ECUIVC_OrderList.m
//  Edu_iOS2018
//
//  Created by yanyan on 2018/1/12.
//  Copyright © 2018年 yanyan. All rights reserved.
//

#import "ECUIVC_OrderList.h"
#import "ECUITVCell_CourseOrder.h"
#import "ECUIVC_OrderDetail.h"
#import "UserInfoManager.h"
#import "ECUIVC_ToComment.h"
#import "ECCourseOrderModel.h"
#import "ECTipCustomView.h"
#import "ECUIVC_Cash.h"
#import "CYUIAlertView.h"
#import "CYDataHelper.h"
#import "ECUIAlertView_CourseDetail.h"
@interface ECUIVC_OrderList()<UITableViewDelegate,UITableViewDataSource,ECTipCustomViewDelegate,DZNEmptyDataSetSource,DZNEmptyDataSetDelegate>
{
    NSURLSessionDataTask *task;
}
@property(nonatomic,strong)UITableView *tableView;
@property(nonatomic,strong)NSMutableArray *dataSourse;
@property(nonatomic,assign)NSInteger curCount;//当前 已经获取的结果数
@property(nonatomic,assign)NSInteger totalCount;//总共有多少记录
@property(nonatomic,strong)ECTipCustomView *cancelView;
@property(nonatomic,strong)ECCourseOrderModel *cancelOrder;
@property(nonatomic,strong)ECUIAlertView_CourseDetail *uiview_alert;
@end

@implementation ECUIVC_OrderList

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.dataSourse = [NSMutableArray array];
    [self requestData];
    
}
-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    if (task && task.state == NSURLSessionTaskStateCompleted) {
        [self refreshOrderList];
    }
}
-(ECTipCustomView *)cancelView
{
    if (!_cancelView) {
       _cancelView = [[ECTipCustomView alloc]init];
       _cancelView.delegate = self;
    }
    return _cancelView;
}
-(void)requestData{
    WeakSelf(weakSelf);
    NSDictionary *params;
    if (self.orderState) {
        params = @{@"start":@(self.curCount),@"limit":@(10),@"status":self.orderState};
    } else {
        params = @{@"start":@(self.curCount),@"limit":@(10)};
    }
    if (!self.orderState) {
        dispatch_async(dispatch_get_main_queue(), ^{
            [MBProgressHUD showHUDAddedTo:[[UIApplication sharedApplication] keyWindow] animated:YES];
        });
    }
   task = [HWHttpTool requestWithMethod:@"GET" url:URL_CourseOrderList params:params headers:@{@"X-AUTH-TOKEN":[UserInfoManager shareUser].token} success:^(id json) {
        [weakSelf reloadData:json];
    } failure:^(NSError *error) {
        dispatch_async(dispatch_get_main_queue(), ^{
            [MBProgressHUD hideHUD];
            [MBProgressHUD showWarnMessage:@"请求订单列表失败"];
        });
        
    }];
   
}
- (void)reloadData:(id)jsonData{
    
    dispatch_async(dispatch_get_global_queue( DISPATCH_QUEUE_PRIORITY_LOW, 0), ^{
        // Do something...
        if (jsonData) {
            if (self.curCount == 0) {
                [self.dataSourse removeAllObjects];
            }
            
            if ([[jsonData  valueForKey:@"code"] integerValue] == 401) {
                [self showAlertViewWithJson:jsonData];
            } else {
                id data = [[jsonData valueForKey:@"data"] valueForKey:@"resources"];
                [self.dataSourse addObjectsFromArray:[ECModelData arrayForCategoryOrderList:data]];
                self.totalCount = [[[jsonData valueForKey:@"data"] valueForKey:@"total"] integerValue];
                self.curCount = self.dataSourse.count;
            }
        }
        dispatch_async(dispatch_get_main_queue(), ^{
            [MBProgressHUD hideHUD];
            [self endRefreshHeader];
            [self endLoadMoreFooterWithLoadMore:(self.curCount < self.totalCount)];
            [self.tableView reloadData];

        });
    });

    
       
       
    
}
-(void)showAlertViewWithJson:(id)json
{
    CYUIAlertView * alter = [[CYUIAlertView alloc]initWithAlertViewTitle:@"提示" message:[json valueForKey:@"message"] cancelButtonTitle:@"返回去登录" otherButtonTitles: nil];
    alter.block_cancel = ^{
        DLog(@"%@",@"取消");
        [UserInfoManager loginOut];
        [self.navigationController popViewControllerAnimated:YES];
    };
  
    [alter showAlertViewInViewController:self];
}
- (void)addSubviews
{
    [super addSubviews];
    [self.view addSubview:self.tableView];
}
- (UITableView *)tableView{
    if (!_tableView) {
        _tableView = [[UITableView alloc]initWithFrame:self.view.bounds style:UITableViewStylePlain];
        _tableView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
        [_tableView registerClass:[ECUITVCell_CourseOrder class] forCellReuseIdentifier:@"cell"];
        [_tableView registerClass:[UITableViewHeaderFooterView class] forHeaderFooterViewReuseIdentifier:@"header"];
        _tableView.rowHeight = kProportion_Height(526);
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableView.delegate = self;
        _tableView.emptyDataSetSource = self;
        _tableView.emptyDataSetDelegate = self;
        _tableView.dataSource = self;
        WeakSelf(weakSelf);
        _tableView.mj_header = [MJRefreshStateHeader headerWithRefreshingBlock:^{
            [weakSelf refreshOrderList];
        }];
        MJRefreshBackNormalFooter *footer = [MJRefreshBackNormalFooter footerWithRefreshingBlock:^{
            
            [weakSelf loadMoreOrderList];
        }];
        _tableView.mj_footer = footer;
    }
    return _tableView;
}
#pragma mark - 刷新数据 -
-(void)refreshOrderList{
    self.curCount = 0;
    [self requestData];
}
-(void)loadMoreOrderList{
    [self requestData];
}
- (void)endRefreshHeader{
//    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
//        // 拿到当前的下拉刷新控件，结束刷新状态
//        DLog(@"刷新成功");
        [self.tableView.mj_header endRefreshing];
//    });
}

#pragma mark - 无数据 -
- (UIImage *)imageForEmptyDataSet:(UIScrollView *)scrollView{
    return [UIImage imageNamed:@"image_order_nodata"];
}
- (NSAttributedString *)buttonTitleForEmptyDataSet:(UIScrollView *)scrollView forState:(UIControlState)state
{
    if (self.orderState) {
        NSString *tips = @"暂无待支付课程订单";
        if ([self.orderState isEqualToString:@"paid"]) {
            tips = @"暂无已支付课程订单";
        }
        NSMutableAttributedString *attrStr = [[NSMutableAttributedString alloc] initWithString:tips];
        [attrStr addAttributes:@{NSForegroundColorAttributeName:[UIColor colorWithHexString:@"#b3b3b3"],NSFontAttributeName:[UIFont systemFontOfSize:16]} range:NSMakeRange(0,tips.length)];
        
        return attrStr;
    } else{
    NSMutableAttributedString *attrStr = [[NSMutableAttributedString alloc] initWithString:@"暂无课程订单,现在【去选课】"];
        [attrStr addAttributes:@{NSForegroundColorAttributeName:[UIColor colorWithHexString:@"#b3b3b3"],NSFontAttributeName:[UIFont systemFontOfSize:16]} range:NSMakeRange(0,9)];
        [attrStr addAttributes:@{NSForegroundColorAttributeName:[UIColor colorWithHexString:@"#FF6800"],NSFontAttributeName:[UIFont systemFontOfSize:16]} range:NSMakeRange(9,5)];

        return attrStr;
    }
}
- (void)emptyDataSet:(UIScrollView *)scrollView didTapButton:(UIButton *)button
{
    if (!self.orderState) {
        if (self.block_empty) {
            self.block_empty();
        }
    }
}
- (void)endLoadMoreFooterWithLoadMore:(BOOL)canLoadMore{
    WeakSelf(weakSelf);
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        if (canLoadMore) {
            [weakSelf.tableView.mj_footer endRefreshing];

        } else {
            self.tableView.mj_footer.state = MJRefreshStateNoMoreData;
        }
    });
}
#pragma mark - TableViewDelegate -
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.dataSourse.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITVCell_base *cell = [tableView dequeueReusableCellWithIdentifier:@"cell" forIndexPath:indexPath];
    cell.object = [self.dataSourse objectAtIndex:indexPath.row];
    WeakSelf(weakSelf);
    ((ECUITVCell_CourseOrder *)cell).block_right = ^(id obj) {
        [weakSelf showOrderRightOperationVC:obj];
    };
    ((ECUITVCell_CourseOrder *)cell).block_left = ^(id obj) {
        [weakSelf showOrderLeftOperationVC:obj];
    };
    return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    ECCourseOrderModel *mo = [self.dataSourse objectAtIndex:indexPath.row];
    CourseModel *mo_selected = mo.mo_course;
    if ([CYDataHelper isNull:mo_selected.modelId] || mo_selected.deleted) {
        [self showAlertViewWithTitle:@"抱歉，课程已删除无法购买或学习。如有疑问请咨询客服。"];
        return;
    }
    ECUIVC_OrderDetail *uivc = [[ECUIVC_OrderDetail alloc]init];
    uivc.object = [self.dataSourse objectAtIndex:indexPath.row];
    [self.navigationController pushViewController:uivc animated:YES];
}

#pragma mark - TableViewDelegate -


#pragma mark - Cell btn selected -
- (void)showOrderRightOperationVC:(id)obj
{
    ECCourseOrderModel *mo = obj;
    CourseModel *mo_selected = mo.mo_course;
    if ([CYDataHelper isNull:mo_selected.modelId] || mo_selected.deleted) {
        [self showAlertViewWithTitle:kAlertTipOfCourseDelete];
        return;
    }
    if (![mo_selected.status isEqualToString:@"published"]) {
        [self showAlertViewWithTitle:kAlertTipOfCourseClosed];
        return;
        
    }
    if ([mo.orderState isEqualToString:@"created"]) {
        //待支付
       ECUIVC_Cash *uivc_pay = [[ECUIVC_Cash alloc]init];
        uivc_pay.object = mo;
        [self.navigationController pushViewController:uivc_pay animated:YES];
    } else if ([mo.orderState isEqualToString:@"paid"]) {
        if (mo.reviewed) {
            //已完成- 查看评价
            
        } else {
            //待评价- 去评价
            ECUIVC_ToComment *uivc_toComment = [[ECUIVC_ToComment alloc]init];
            uivc_toComment.object = obj;
            [self.navigationController pushViewController:uivc_toComment animated:YES];
        }
        
    }
}
- (void)showOrderLeftOperationVC:(id)obj
{
    ECCourseOrderModel *mo = obj;
    CourseModel *mo_selected = mo.mo_course;
    if ([CYDataHelper isNull:mo_selected.modelId] || mo_selected.deleted) {
        [self showAlertViewWithTitle:kAlertTipOfCourseDelete];
        return;
    }
//    if (![mo_selected.status isEqualToString:@"published"]) {
//        [self showAlertViewWithTitle:@"抱歉，课程已关闭无法进行购买学习。如有疑问请咨询客服。"];
//        return;
//
//    }
    // 取消订单
    self.cancelOrder = obj;
    [self.cancelView showTipviewWithTpe:tipTypeOfCancelOrder andIndexPath:0];
}
-(void)tipCustomViewOfSureBtnClickWithRow:(NSInteger)row{
    //执行删除
    WeakSelf(weakSelf);
    [HWHttpTool requestWithMethod:@"POST" url:URL_CancelCourseOrderWithId(self.cancelOrder.orderId) params:nil headers:@{URL_SERVER_HEADER_USERTOKEN_KEY:[[UserInfoManager shareUser] token]} success:^(id json) {
        [MBProgressHUD showSuccessMessage:@"取消订单成功"];
        [weakSelf refreshOrderList];
    } failure:^(NSError *error) {
        NSString  *data = [error.userInfo valueForKey:@"com.alamofire.serialization.response.error.string"];
        [MBProgressHUD showErrorMessage:data];
    }];

}
- (void)showAlertViewWithTitle:(NSString *)title
{
   NSMutableAttributedString *attributeString = [[NSMutableAttributedString alloc]initWithString:title attributes:@{NSFontAttributeName: [UIFont boldSystemFontOfSize:18.0f],NSForegroundColorAttributeName: [UIColor colorWithHexString:@"#000000"]}];
    _uiview_alert = [[ECUIAlertView_CourseDetail alloc]initWithTitle:attributeString cancleTitle:@"确定" confirmTitle: nil];
    [_uiview_alert showAlert];
    
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
